﻿using Newtonsoft.Json;
using P2P.Stun.Model;
using P2P.Network;
using P2P.Network.ExtensionMethods;
using P2P.Network.SocketServer;
using System.Net.Sockets;
using System.Text;
using P2P.Stun.Util;

namespace P2P.Stun
{
    public sealed class AppBuilder
    {
        private AppBuilder() { }

        private void UdpReceivedCallback(Socket sender, DataEventArgs e) 
        {
            try 
            {
                byte[] buffer = e.Data;
                string bufStr = Encoding.UTF8.GetString(buffer);

                object result = ApiHandler.Process(sender, e.RemoteEndPoint, bufStr);

                if (result != null)
                {
                    string msg = JsonConvert.SerializeObject(result, Formatting.None);

                    sender.SendTo(msg, e.RemoteEndPoint);
                }
            }
            catch (Exception ex) 
            {
                Logger.WriteError(ex.Message);
            }
           
        }

        public void Start()
        {
            UDPSocketListener UdpSocketListener = new UDPSocketListener(SharedModel.Instance.Hosts.UDPStunServerIP,
                SharedModel.Instance.Hosts.UDPStunServerPort.Value, UdpReceivedCallback);
            UdpSocketListener.Start();

            Console.WriteLine("请输入字符串，输入 q 退出：");

            while (true)
            {
                string input = Console.ReadLine();

                if (input == "q")
                {
                    UdpSocketListener.Stop();
                    break;
                }
            }
        }

        public static AppBuilder Configure(Hosts hosts) 
        {
            SharedModel.Instance.Hosts = hosts;
            return new AppBuilder();
        }
    }
}
